<?php

namespace App\Http\Controllers\Api;

use App\BooksChapter;
use App\BooksInfo;
use App\Classify;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\User;
use App\UserBooks;
use App\UserReadingRecord;
use App\UserVip;
use App\VipRule;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class BooksController extends Controller
{
    /**
     * 获取读物列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBooksInfoList(Request $request){
        /** @var User $user */
       $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $limit        = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page         = !is_null($request->get('page')) ? $request->get('page') : 0;
        $classify_id  = !is_null($request->get('classify_id'))?$request->get('classify_id'):0;
        $type         = $request->get('type');
        $name         = $request->get('name');


        if(is_null($type) || $type == ''){
            if(!is_null($name) && $name != ''){
                $booksInfoList = BooksInfo::whereStatus(1)->where('name','like','%'.$name.'%')->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
            }else{
                $booksInfoList = BooksInfo::whereStatus(1)->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
            }
            $recommendNum = BooksInfo::whereStatus(1)->whereHomeShow(1)->count();
            $featuredNum = BooksInfo::whereStatus(1)->whereIsFeatured(1)->count();
            if ($classify_id!==0){
                $booksInfoList = BooksInfo::whereStatus(1)->whereClassifyId($classify_id)->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
                $recommendNum = BooksInfo::whereStatus(1)->whereClassifyId($classify_id)->whereHomeShow(1)->count();
                $featuredNum = BooksInfo::whereStatus(1)->whereClassifyId($classify_id)->whereIsFeatured(1)->count();
            }

        }


        else{
            $booksInfoList = BooksInfo::whereStatus(1)->whereType($type)->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
            $recommendNum = BooksInfo::whereStatus(1)->whereHomeShow(1)->whereType($type)->count();
            $featuredNum = BooksInfo::whereStatus(1)->whereIsFeatured(1)->whereType($type)->count();
        }

        /** @var BooksInfo $booksInfo */
        if(count($booksInfoList) > 0){
            foreach($booksInfoList as $booksInfo){
                $booksInfo->img_utl = FileManager::getImgUrl($booksInfo->img_id);

                if($booksInfo->is_complete == 0){
                    $booksInfo->is_complete = '连载中';
                }else{
                    $booksInfo->is_complete = '完结';
                }

                $thisUserBooks = UserBooks::whereUserId($user->id)->whereBooksInfoId($booksInfo->id)->first();
                if($thisUserBooks){
                    $booksInfo->is_buy = 1;
                }else{
                    $booksInfo->is_buy = 0;
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $booksInfoList,'recommend_count' => $recommendNum,'featured_count' => $featuredNum]);
    }

    /**
     * 获取章节列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBooksChapterList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $booksInfoId = $request->get('books_info_id');
        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 0;

        /** @var BooksInfo $thisBooksInfo */
        $thisBooksInfo = BooksInfo::whereId($booksInfoId)->whereStatus(1)->first();
        if(!$thisBooksInfo)
            return response()->json(['level' => 'error','message' => '该读物已下架']);

        $chapterNameArr = array();
        /** @var BooksChapter $booksChapter */
        $booksChapters = BooksChapter::whereStatus(1)->whereBooksInfoId($thisBooksInfo->id)->orderBy('sort','asc')->offset($limit * $page)->limit($limit)->get();
        if(count($booksChapters) > 0){
            foreach($booksChapters as $booksChapter){
                if($user->is_free != 1) {
                    $thisUserBooks = UserBooks::whereUserId($user->id)->whereBooksInfoId($thisBooksInfo->id)->whereBooksChapterId(0)->first();
                    if ($thisUserBooks) {
                        $isBuy = 1;
                    } else {
                        /** @var UserVip $thisGlobalVip */
                        $thisGlobalVip = UserVip::whereUserId($user->id)->whereType('global_vip')->first();

                        /** @var UserVip $thisClassifyVip */
                        $thisClassifyVip = UserVip::whereUserId($user->id)->whereType('classify_vip')->whereClassifyId($thisBooksInfo->classify_id)->first();
                        if(($thisGlobalVip && (strtotime($thisGlobalVip->end_time) >= time() || $thisGlobalVip->end_time == "0000-00-00 00:00:00")) || ($thisClassifyVip && (strtotime($thisClassifyVip->end_time) >= time() || $thisClassifyVip->end_time == "0000-00-00 00:00:00"))) {
                            $isBuy = 1;
                        }else{
                            $thisUserBooks = UserBooks::whereUserId($user->id)->whereBooksInfoId($thisBooksInfo->id)->whereBooksChapterId($booksChapter->id)->first();
                            if($thisUserBooks){
                                $isBuy = 1;
                            }else{
                                $isBuy = 0;
                            }
                        }
                    }
                }else{
                    $isBuy = 1;
                }

                $chapterName = (object)['id' => $booksChapter->id,'name' => $booksChapter->name,'is_buy' => $isBuy];
                array_push($chapterNameArr,$chapterName);
            }
        }

        $thisBooksInfo->img_utl = FileManager::getImgUrl($thisBooksInfo->img_id);

        if($thisBooksInfo->is_complete == 0){
            $thisBooksInfo->is_complete = '连载中';
        }else{
            $thisBooksInfo->is_complete = '完结';
        }

        if($user->is_free != 1) {
            $thisUserBooks = UserBooks::whereUserId($user->id)->whereBooksInfoId($thisBooksInfo->id)->whereBooksChapterId(0)->first();
            if ($thisUserBooks) {
                $thisBooksInfo->is_buy = 1;
            } else {
                /** @var UserVip $thisGlobalVip */
                $thisGlobalVip = UserVip::whereUserId($user->id)->whereType('global_vip')->first();

                /** @var UserVip $thisClassifyVip */
                $thisClassifyVip = UserVip::whereUserId($user->id)->whereType('classify_vip')->whereClassifyId($thisBooksInfo->classify_id)->first();
                if(($thisGlobalVip && (strtotime($thisGlobalVip->end_time) >= time() || $thisGlobalVip->end_time == "0000-00-00 00:00:00")) || ($thisClassifyVip && (strtotime($thisClassifyVip->end_time) >= time() || $thisClassifyVip->end_time == "0000-00-00 00:00:00"))) {
                    $thisBooksInfo->is_buy = 1;
                }else{
                    $thisBooksInfo->is_buy = 0;
                }
            }
        }else{
            $thisBooksInfo->is_buy = 1;
        }

        $totalArticleNum = BooksChapter::whereStatus(1)->whereBooksInfoId($thisBooksInfo->id)->count();

        $thisBooksInfo->total_article_num = $totalArticleNum;

        $thisBooksInfo->books_chapter = $chapterNameArr;

        return response()->json(['level' => 'success','message' => '获取成功','data' => $thisBooksInfo]);
    }

    /**
     * 获取章节内容
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBooksChapterContent(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $booksInfoId    = !is_null($request->get('books_info_id')) ? $request->get('books_info_id') : 0;
        $booksChapterId = !is_null($request->get('books_chapter_id')) ? $request->get('books_chapter_id') : 0;

        /** @var BooksInfo $thisBooksInfo */
        $thisBooksInfo = BooksInfo::whereId($booksInfoId)->whereStatus(1)->first();
        if(!$thisBooksInfo)
            return response()->json(['level' => 'error','message' => '该读物已下架']);

        if($user->is_free == 1){
            if($thisBooksInfo->type == 'word'){
                /** @var BooksChapter $booksChapters */
                $booksChapters = BooksChapter::whereBooksInfoId($thisBooksInfo->id)->whereId($booksChapterId)->whereStatus(1)->first();
                if(!$booksChapters){
                    return response()->json(['level' => 'error','message' => '该章节已下架']);
                }

                $booksChapters->content = str_replace("/uploads/ueditor/php/upload/image",env('HOST_URL')."/uploads/ueditor/php/upload/image",$booksChapters->content);
            }else{
                /** @var BooksChapter $booksChapters */
                $booksChapters = BooksChapter::whereBooksInfoId($thisBooksInfo->id)->whereId($booksChapterId)->whereStatus(1)->first();
                if($booksChapters){
                    $booksChapters->audio_url = FileManager::getAudioUrl($booksChapters->audio_id);
                }else{
                    return response()->json(['level' => 'error','message' => '该章节已下架']);
                }
            }

            /** @var BooksChapter $previousBooksChapter */
            $previousBooksChapter = BooksChapter::whereBooksInfoId($thisBooksInfo->id)->whereStatus(1)->where('sort','<',$booksChapters->sort)->orderBy('id','desc')->first();

            /** @var BooksChapter $nextBooksChapter */
            $nextBooksChapter = BooksChapter::whereBooksInfoId($thisBooksInfo->id)->whereStatus(1)->where('sort','>',$booksChapters->sort)->first();

            $result['books_chapter_info']  = $booksChapters;
            $result['previous_books_chapter'] = $previousBooksChapter ? $previousBooksChapter->id : null;
            $result['next_books_chapter']     = $nextBooksChapter ? $nextBooksChapter->id : null;
        }else{
            /** @var UserVip $thisGlobalVip */
            $thisGlobalVip = UserVip::whereUserId($user->id)->whereType('global_vip')->first();

            /** @var UserVip $thisClassifyVip */
            $thisClassifyVip = UserVip::whereUserId($user->id)->whereType('classify_vip')->whereClassifyId($thisBooksInfo->classify_id)->first();
            if(($thisGlobalVip && (strtotime($thisGlobalVip->end_time) >= time() || $thisGlobalVip->end_time == "0000-00-00 00:00:00")) || ($thisClassifyVip && (strtotime($thisClassifyVip->end_time) >= time() || $thisClassifyVip->end_time == "0000-00-00 00:00:00"))){
                if($thisBooksInfo->type == 'word'){
                    /** @var BooksChapter $booksChapters */
                    $booksChapters = BooksChapter::whereBooksInfoId($thisBooksInfo->id)->whereId($booksChapterId)->whereStatus(1)->first();
                    if(!$booksChapters){
                        return response()->json(['level' => 'error','message' => '该章节已下架']);
                    }

                    $booksChapters->content = str_replace("/uploads/ueditor/php/upload/image",env('HOST_URL')."/uploads/ueditor/php/upload/image",$booksChapters->content);
                }else{
                    /** @var BooksChapter $booksChapters */
                    $booksChapters = BooksChapter::whereBooksInfoId($thisBooksInfo->id)->whereId($booksChapterId)->whereStatus(1)->first();
                    if($booksChapters){
                        $booksChapters->audio_url = FileManager::getAudioUrl($booksChapters->audio_id);
                    }else{
                        return response()->json(['level' => 'error','message' => '该章节已下架']);
                    }
                }

                /** @var BooksChapter $previousBooksChapter */
                $previousBooksChapter = BooksChapter::whereBooksInfoId($thisBooksInfo->id)->whereStatus(1)->where('sort','<',$booksChapters->sort)->orderBy('id','desc')->first();

                /** @var BooksChapter $nextBooksChapter */
                $nextBooksChapter = BooksChapter::whereBooksInfoId($thisBooksInfo->id)->whereStatus(1)->where('sort','>',$booksChapters->sort)->first();

                $result['books_chapter_info']  = $booksChapters;
                $result['previous_books_chapter'] = $previousBooksChapter ? $previousBooksChapter->id : null;
                $result['next_books_chapter']     = $nextBooksChapter ? $nextBooksChapter->id : null;
            }else{
                /** @var BooksChapter $thisBooksChapterInfo */
                $thisBooksChapterInfo = BooksChapter::whereBooksInfoId($thisBooksInfo->id)->whereId($booksChapterId)->whereStatus(1)->first();
                if(!$thisBooksChapterInfo)
                    return response()->json(['level' => 'error','message' => '该章节已下架']);

                $thisUserBooks = UserBooks::whereUserId($user->id)->whereBooksInfoId($thisBooksInfo->id)->whereBooksChapterId(0)->first();

                $thisUserBooksChapter = UserBooks::whereUserId($user->id)->whereBooksInfoId($thisBooksInfo->id)->whereBooksChapterId($booksChapterId)->first();
                if (!$thisUserBooks && !$thisUserBooksChapter){
                    $thisBooksChapter = BooksChapter::whereBooksInfoId($booksInfoId)->orderBy('id','asc')->lists('id');
                    if($thisBooksChapter[0] != $booksChapterId && $thisBooksChapter[1] != $booksChapterId)
                        return response()->json(['level' => 'error','message' => '您还没购买本章节','data' => 'no_buy','books_chapter_coin' => $thisBooksChapterInfo->books_coin_price]);
                }

                if($thisBooksInfo->type == 'word'){
                    /** @var BooksChapter $booksChapters */
                    $booksChapters = BooksChapter::whereBooksInfoId($thisBooksInfo->id)->whereId($booksChapterId)->whereStatus(1)->first();
                    if(!$booksChapters){
                        return response()->json(['level' => 'error','message' => '该章节已下架']);
                    }

                    $booksChapters->content = str_replace("/uploads/ueditor/php/upload/image",env('HOST_URL')."/uploads/ueditor/php/upload/image",$booksChapters->content);
                }else{
                    /** @var BooksChapter $booksChapters */
                    $booksChapters = BooksChapter::whereBooksInfoId($thisBooksInfo->id)->whereId($booksChapterId)->whereStatus(1)->first();
                    if($booksChapters){
                        $booksChapters->audio_url = FileManager::getAudioUrl($booksChapters->audio_id);
                    }else{
                        return response()->json(['level' => 'error','message' => '该章节已下架']);
                    }
                }

                /** @var BooksChapter $previousBooksChapter */
                $previousBooksChapter = BooksChapter::whereBooksInfoId($thisBooksInfo->id)->whereStatus(1)->where('sort','<',$booksChapters->sort)->orderBy('id','desc')->first();

                /** @var BooksChapter $nextBooksChapter */
                $nextBooksChapter = BooksChapter::whereBooksInfoId($thisBooksInfo->id)->whereStatus(1)->where('sort','>',$booksChapters->sort)->first();

                $result['books_chapter_info']  = $booksChapters;
                $result['previous_books_chapter'] = $previousBooksChapter ? $previousBooksChapter->id : null;
                $result['next_books_chapter']     = $nextBooksChapter ? $nextBooksChapter->id : null;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $result]);
    }

    /**
     * 保存用户阅读记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function saveReadingRecord(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $booksInfoId    = $request->get('books_info_id');
        $booksChapterId = $request->get('books_chapter_id');

        /** @var BooksInfo $thisBooksInfo */
        $thisBooksInfo = BooksInfo::whereId($booksInfoId)->first();
        if(!$thisBooksInfo)
            return response()->json(['level' => 'error','message' => '该读物不存在']);

        /** @var BooksChapter $thisBooksChapter */
        $thisBooksChapter = BooksChapter::whereId($booksChapterId)->first();
        if(!$thisBooksChapter)
            return response()->json(['level' => 'error','message' => '该章节不存在']);

        if($thisBooksChapter->books_info_id != $thisBooksInfo->id)
            return response()->json(['level' => 'error,','message' => '该章节与读物不匹配']);

        $newUserReadingRecord = new UserReadingRecord();
        $newUserReadingRecord->user_id          = $user->id;
        $newUserReadingRecord->books_info_id    = $thisBooksInfo->id;
        $newUserReadingRecord->books_chapter_id = $thisBooksChapter->id;
        $newUserReadingRecord->read_time        = date('Y-m-d H:i:s',time());
        $newUserReadingRecord->save();

        return response()->json(['level' => 'success','message' => '收藏成功','data' => $newUserReadingRecord]);
    }

    public  function getClassify(Request $request){
//        $user = UserManager::isLogin($request);
//        if(!$user)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        /** @var Classify $classify */
        $classifies=Classify::orderBy("created_at","sort")->get();
//        if(count($classifies) > 0){
//            foreach($classifies as $classify){
//                /** @var UserVip $thisGlobalVip */
//                $thisGlobalVip = UserVip::whereUserId($user->id)->whereType('global_vip')->first();
//
//                /** @var UserVip $thisClassifyVip */
//                $thisClassifyVip = UserVip::whereUserId($user->id)->whereType('classify_vip')->whereClassifyId($classify->id)->first();
//                if(($thisGlobalVip && (strtotime($thisGlobalVip->end_time) >= time() || $thisGlobalVip->end_time == "0000-00-00 00:00:00")) || ($thisClassifyVip && (strtotime($thisClassifyVip->end_time) >= time() || $thisClassifyVip->end_time == "0000-00-00 00:00:00"))){
//                    $classify->is_buy = 1;
//                }else{
//                    $classify->is_buy = 0;
//                }
//            }
//        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $classifies]);
    }
}
